package com.wang.tool.mybatis;

import com.wang.tool.monitor.LinkLogUtil;
import com.wang.tool.util.CommonUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * mybatis的带getCode函数的Enum枚举解析类
 *
 * @param <E>
 * @author wangshaopeng
 */
public class GetCodeEnumTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {

    private final Method method;
    private final Map<String, Enum<E>> str2Enum = new HashMap<>();

    public GetCodeEnumTypeHandler(Class<E> type) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        method = type.getMethod("getCode");
        for (Enum oEnum : type.getEnumConstants()) {
            Object code = method.invoke(oEnum);
            if (code != null) {
                str2Enum.put(code.toString().trim(), oEnum);
            }
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        Object o;
        try {
            o = method.invoke(parameter);
        } catch (IllegalAccessException | InvocationTargetException e) {
            LinkLogUtil.newTagLog("EnumGetCodeError")
                    .log();
            throw new RuntimeException(parameter + "can not getCode");
        }
        if (jdbcType == null) {
            ps.setObject(i, o);
        } else {
            ps.setObject(i, o, jdbcType.TYPE_CODE);
        }
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return deduceByResultSet(rs.getString(columnName));
    }


    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return deduceByResultSet(rs.getString(columnIndex));
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return deduceByResultSet(cs.getString(columnIndex));
    }

    /**
     * 转换
     *
     * @param val
     * @return
     */
    private E deduceByResultSet(String val) {
        if (CommonUtil.isBlank(val)) {
            return null;
        }
        //清除两边空格
        val = val.trim();
        return (E) str2Enum.get(val);
    }

}